# -*- coding: utf-8 -*-
# @Date    : 2015-06-21 15:50:35
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

from lib.tornado_routes import route
from web.handler import BaseHandler
from tornado import gen
from tornado.web import asynchronous
from functools import wraps
from web.models.admin.user.student import Student
from web.models.admin.user.teacher import Teacher
import json
import time
import md5
import base64
from lib import libupload

@route(r'/admin/user/teacher/?', name='teacher.index')
class IndexHandler(BaseHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        cur_page = self.get_argument('page', default=1)
        school_id = self.get_argument('schoolId', default=self.school_id)

        school = self.get_cookie('school', base64.b16encode('{}'))
        school = json.loads(base64.b16decode(school))
        dt = school.get('teacher', {})
        tname = dt.get('tname', '')

        where = {
            "Fname":   tname,
        }

        page = (int(cur_page) - 1) * self.offset

        ret, count = yield Teacher().select_teacher(school_id, where, page, self.offset)

        page_info = {'total': count, 'page': int(cur_page)}
        self.render("admin/user/teacher/list.html", data=ret, page_info=page_info, where=where)

    @asynchronous
    @gen.coroutine
    def post(self):
        cur_page = self.get_argument('page', default='1')
        school_id = self.get_argument('schoolId', default=self.school_id)
        tname = self.get_argument('tname', default='')

        school = self.get_cookie('school', base64.b16encode('{}'))
        school = json.loads(base64.b16decode(school))
        dt = school.get('teacher', {})
        if tname != '':
            dt['tname'] = tname
        else:
            dt.pop('tname', '')

        school["teacher"] = dt
        self.set_cookie('school', base64.b16encode(json.dumps(school)))
        
        self.redirect('/admin/user/teacher/')


@route(r'/admin/user/teacher/new/?', name='teacher.new')
class NewHandler(BaseHandler):
    @asynchronous
    @gen.coroutine
    def get(self):

        school_id = self.get_argument('schoolId', default=self.school_id)

        school = yield Student().select_school(school_id)

        self.render("admin/user/teacher/new.html", school=school)


    @asynchronous
    @gen.coroutine
    def post(self):
        ltype = self.get_argument('ltype', default='0')
        school_id = self.get_argument('schoolId', default=self.school_id)
        Ftel = self.get_argument('Ftel', default='')
        Fname = self.get_argument('Fname', default='')
        Fusername = self.get_argument('Fusername', default='')
        Fage = self.get_argument('Fage', default='0')
        Fpasswd = self.get_argument('Fpasswd', default='')
        Fmajor_id = self.get_argument('Fmajor_id', default='0')
        Favatar = self.get_argument('Favatar', default='')
        Faddress = self.get_argument('Faddress', default='')
        Favatar = self.request.files.get('Favatar')

        if Favatar is not None:
            Favatar, path = libupload.save(Favatar[0])
            libupload.img.thumbnail(path, path, 100, 100)
        else:
            Favatar = ""

        teacher_data = {
            "Fuser_name":   Fusername,
            "Fpwd":         md5.md5(Fpasswd).hexdigest(),
            "Ftype":        2,
            "Fuser_id":     0,
            "Fcreate_time": time.time(),
        }

        teacher_info_data = {
            "Fname":         Fname,
            "Ftel":           Ftel,
            "Fschool_id":      school_id,
            "Fmajor_id":         Fmajor_id,
            "Favatar":          Favatar,
            "Faddress":          Faddress,
            "Fage":    Fage,
            "Fcreate_time":  time.time(),
            "Favatar":       Favatar
        }

        count = yield Teacher().insert_teacher(teacher_data, teacher_info_data)

        if ltype == '0':
            self.redirect('/admin/user/teacher/')
        else:
            self.redirect('/admin/user/teacher/new/')

@route(r'/admin/user/teacher/del/(?P<FteacherId>[0-9].*)/(?P<cur_page>[0-9].*)', name='teacher.del_teacher')
class DelHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, FteacherId, cur_page):
        school_id = self.get_argument('schoolId', default=self.school_id)

        ret = Teacher().del_teacher(FteacherId)

        self.redirect('/admin/user/teacher/?page=' + cur_page)

@route(r'/admin/user/teacher/edit/(?P<Fid>[0-9].*)', name='teacher.edit')
class EditHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, Fid):
        school_id = self.get_argument('schoolId', default=self.school_id)

        teacher = yield Teacher().find_teacher(Fid)
        school = yield Student().select_school(school_id)

        self.render("admin/user/teacher/edit.html", school=school, teacher=teacher)

    @asynchronous
    @gen.coroutine
    def post(self, Fid):
        ltype = self.get_argument('ltype', default='0')
        school_id = self.get_argument('schoolId', default=self.school_id)
        Ftel = self.get_argument('Ftel', default='')
        Fname = self.get_argument('Fname', default='')
        Fusername = self.get_argument('Fusername', default='')
        Fage = self.get_argument('Fage', default='0')
        Fpasswd = self.get_argument('Fpasswd', default='')
        Fmajor_id = self.get_argument('Fmajor_id', default='0')
        Favatar = self.get_argument('Favatar', default='')
        Faddress = self.get_argument('Faddress', default='')
        Favatar = self.request.files.get('Favatar')

        if Favatar is not None:
            Favatar, path = libupload.save(Favatar[0])
            libupload.img.thumbnail(path, path, 100, 100)
        else:
            Favatar = ""

        teacher_info_data = {
            "Fname":         Fname,
            "Ftel":           Ftel,
            "Fschool_id":      school_id,
            "Fmajor_id":         Fmajor_id,
            "Favatar":          Favatar,
            "Faddress":          Faddress,
            "Fage":    Fage,
        }
        if Favatar != "":
            teacher_info_data['Favatar'] = Favatar

        count = yield Teacher().update_teacher(Fid, Fusername, teacher_info_data)


        self.redirect('/admin/user/teacher/')


@route(r'/admin/teacher/result/?')
class ResultHandler(BaseHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        print self.get_argument('param', default=1)
        self.write('asdfsadf')